/*
 * @Author: lsjweiyi 759209794@qq.com
 * @Date: 2024-03-30 14:06:37
 * @LastEditors: lsjweiyi 759209794@qq.com
 * @LastEditTime: 2024-05-03 14:23:39
 * @FilePath: \web-ssg\pages\image\utils.ts
 * @Description: 主要为了抽象一些图像组件里同样逻辑的代码，减少重复代码
 */
import { createDiscreteApi } from "naive-ui";
import type { IResponse } from "~/utils/request";

interface IImgResult {
    base64: string;
    height: number;
    width: number;
}

export function checkFile(file: File, maxSize: number, imgSize: number[] | undefined, suffix = ["image/png", "image/jpeg", "image/bmp"]) {
    const { message } = createDiscreteApi(["message"]);
    return new Promise<IImgResult | undefined>((resolve) => {
        if (!(file?.type && suffix.includes(file?.type))) {
            message.error("上传的文件格式不允许！");
            resolve(undefined);
            return;
        }
        if (file.size > maxSize * 1024) {
            let fileSize = Math.round(file.size / 1024);
            let maxSizeShow = maxSize;
            let unit: string;
            if (maxSize >= 1024) {
                unit = "MB";
                fileSize = Math.round(fileSize / 1024);
                maxSizeShow = Math.round(maxSize / 1024);
            } else {
                unit = "KB";
            }
            message.error(`图片大小为：${fileSize} ${unit}, 不得大于 ${maxSizeShow} ${unit}, 请压缩后重新上传`, {
                duration: 5000,
            });
            resolve(undefined);
            return;
        }
        // 读取图片文件
        let reader = new FileReader();
        reader.readAsDataURL(file);

        // 读取图片是异步方法，成功读取后会执行里面的内容
        reader.onload = function (e) {
            if (typeof e.target?.result != "string") {
                resolve(undefined);
                return;
            }
            //加载图片获取图片真实宽度和高度
            var image = new Image();
            image.onload = function () {
                var width = image.width;
                var height = image.height;
                if (imgSize) {
                    if (width < imgSize[0] || height < imgSize[0] || width > imgSize[1] || height > imgSize[1]) {
                        message.error("图片尺寸最短边至少15px，最长边最大4096px", {
                            duration: 5000,
                        });
                        resolve(undefined);
                        return;
                    }
                }
                resolve({ base64: "data:image/png;base64," + (e.target?.result as string).split(",")[1], width: width, height: height });
            };
            image.src = e.target.result; //img.src 应该是放在 onload 方法后边的, 因为当image的src发生改变，浏览器就会跑去加载这个src里的资源,先告诉浏览器图片加载完要怎么处理，再让它去加载图片
        };
    });
}

export function responseDeal(res: IResponse<string>, title: string, taskId: Ref<string> | undefined, showFlag: Ref<number> | undefined, newImgURL: Ref<string | undefined> | undefined) {
    const { dialog } = createDiscreteApi(["dialog"]);
    if (res.code < 0) {
        dialog.error({
            title: title,
            content: res.data + "。如有疑问请联系管理员，日志id：" + res.logId,
            positiveText: "确定",
            onPositiveClick: () => { },
        });
        return false;
    }
    if (taskId) {
        taskId.value = res.taskId;
    }
    if (showFlag) {
        showFlag.value = 3;
    }
    if (newImgURL) {
        newImgURL.value = res.data as string;
    }
    return true;
}
